import React, { Component } from 'react';
import { Text, Image, View, TextInput, ScrollView, TouchableOpacity } from 'react-native';
import { unitWidth, width } from '../constants/AdapterUtil';
import { MyHeader } from '../components/MyHeader';
import Colors from '../constants/Colors';
import { postFetch } from '../constants/HttpExtension';
import { show } from '../constants/Toast';
import { api_member_info_Certification, api_order_workorder_workorderDetail, api_order_workorder_offer } from '../constants/HttpServices';
import { SubmitButton1, SubmitButton4 } from '../components/Button';
import { MyInput1 } from '../components/Input';
import TextUtil from '../constants/TextUtil';
import { ExamineView } from '../components/EmptyView';
import { HideItem, TextItem, ComponentItem, QuoteItem, SettingItem, ChooseTimeItem } from '../components/Item';
import { CommonModal, CommonModal2, CommonModal3 } from '../components/Modal';
import TimePickerUtil from '../components/TimePicker';
import NavigationService from '../constants/NavigationService';
import FastImage from 'react-native-fast-image';

export default class QuoteScreen extends Component {

    constructor(props) {
        super(props)

        const { navigation } = this.props;
        this.id = navigation.getParam('id', 0);
        this.state = {
            data: {},
            list: [],
            delivery_date: '',
            remark: '',
            money: '0',

            inputValue: [],
        }
    }

    componentDidMount() {
        this.props.navigation.addListener('didFocus', payload => {
            this.getData();
        })
    }

    componentWillUnmount() {
        if (TimePickerUtil.myPicker) {
            TimePickerUtil.myPicker.hide();
        }
    };

    render() {

        let views = []
        for (let i = 0, len = this.state.list.length; i < len; i++) {
            let item = this.state.list[i];

            let ImageArray = [];
            if (item.img) {
                for (let i = 0, len = item.img.length; i < len; i++) {
                    let imgItem = item.img[i];
                    ImageArray.push(
                        <TouchableOpacity key={i} style={{ width: 95 * unitWidth, height: 72 * unitWidth, marginRight: 10 * unitWidth }}
                            activeOpacity={0.7} onPress={() => { NavigationService.navigate('BigImageList', { imageList: item.img }) }}>
                            <FastImage
                                style={{ width: 95 * unitWidth, height: 72 * unitWidth }}
                                source={{ uri: imgItem }} resizeMode={FastImage.resizeMode.cover} />
                        </TouchableOpacity>
                    );
                }
            }

            views.push(
                <View>
                    <View style={{ height: 40 * unitWidth, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }}>
                        <Text style={{ color: Colors.black, fontSize: 15 }}>{i + 1}.{item.name + '(' + item.count + '个)'}</Text>
                        <TextInput
                            style={{
                                color: Colors.black, fontSize: 15,
                                textAlign: 'right'
                            }}
                            onChangeText={(text) => {
                                let newText = TextUtil.getTextInput(text, 1)
                                this.state.inputValue[i] = newText
                                this.setState({
                                    inputValue: this.state.inputValue
                                }, () => {
                                    let temp = 0
                                    for (let iterator of this.state.inputValue) {
                                        temp += parseInt(iterator ? iterator : '0')
                                    }
                                    this.setState({
                                        money: temp
                                    })
                                })
                            }}
                            keyboardType='numeric'
                            maxLength={30}
                            placeholder='请输入报价金额'
                            value={this.state.inputValue[i]}
                        />
                    </View>
                    <Text>{'预算金额：' + item.money + '        加工数量：' + item.count} </Text>
                    {item.img && item.img.length > 0 ?
                        <View style={{
                            alignSelf: 'stretch',
                            alignItems: 'center',
                            flexDirection: 'row',
                            flexWrap: 'wrap',
                            marginVertical: 10 * unitWidth
                        }}>
                            {ImageArray}
                        </View> :
                        null}
                </View>
            );
        }

        return (
            <View style={{ flex: 1, backgroundColor: Colors.colorEF }}>
                <MyHeader title='我要报价' leftImg={require('../res/ic_arrow_left.png')} leftClick={() => { this.props.navigation.pop() }} />
                <ScrollView style={{ flex: 1 }} showsVerticalScrollIndicator={false}>
                    <View>
                        <View style={{
                            width: width, paddingHorizontal: 20 * unitWidth,
                            backgroundColor: Colors.white, alignItems: 'flex-start', paddingTop: 15 * unitWidth
                        }}>
                            <Text style={{ color: Colors.black, fontSize: 15 }}>零部件清单：</Text>
                            <View style={{
                                width: 335 * unitWidth, backgroundColor: Colors.colorEF,
                                borderRadius: 10, marginTop: 10 * unitWidth, paddingHorizontal: 12 * unitWidth
                            }}>
                                {views}
                            </View>
                            <View style={{ alignSelf: 'stretch', height: 40 * unitWidth, backgroundColor: Colors.white, flexDirection: 'row', alignItems: 'center', justifyContent: 'flex-end' }}>
                                <Text style={{ fontSize: 15, color: Colors.colorOrange }}>合计：<Text style={{ fontSize: 20 }}>￥{this.state.money}</Text></Text>
                            </View>
                            <View style={{ backgroundColor: Colors.colorEF, width: width, alignSelf: 'center', height: 0.5, marginTop: 10 * unitWidth, position: 'absolute', bottom: 0 }} />
                        </View>
                        <ChooseTimeItem
                            title='交货日期：'
                            tips='请选择交货日期'
                            time={this.state.delivery_date}
                            onChooseSuccess={(data) => {
                                this.setState({
                                    delivery_date: data
                                })
                            }} />
                        <MyInput1
                            style={{ marginTop: 0 * unitWidth }}
                            onChangeText={(text) => { this.setState({ remark: text }) }}
                            title={
                                <Text style={{ color: Colors.black, fontSize: 15 }}>补充说明：</Text>
                            }
                            maxLength={100}
                            placeholder='请补充说明'
                            value={this.state.remark} isLast={false} />
                        {/* <TextItem title='总预算(含税)：' value={this.state.data.general_budget} isLast={false} /> */}
                        {this.state.data.file && this.state.data.file.length > 0 ?
                            <View style={{
                                width: width, paddingLeft: 20 * unitWidth,
                                backgroundColor: Colors.white, alignItems: 'flex-start', paddingTop: 15 * unitWidth
                            }}>
                                <Text style={{ color: Colors.black, fontSize: 15 }}>附件</Text>
                                <View style={{
                                    alignSelf: 'stretch',
                                    alignItems: 'center',
                                    flexDirection: 'row',
                                    flexWrap: 'wrap',
                                    marginVertical: 15 * unitWidth
                                }}>
                                    {this.getFileImageView()}
                                </View>
                            </View> : null}
                        <SubmitButton1 style={{ alignSelf: 'center', marginTop: 70 * unitWidth }} text='立即报价' onPress={() => {
                            this.submit()
                        }} />
                    </View>
                </ScrollView>
                <CommonModal3 ref='CommonModal3' title={'恭喜你报价成功\n请在个人中心查看中标情况'} btnText='确定'
                    onPress={() => {
                        this.refs.CommonModal3.hideModal();
                        this.props.navigation.pop();
                    }}
                    onClosePress={() => {
                        this.props.navigation.pop();
                    }} />
            </View>
        );
    }

    getData() {
        let params = {
            'id': this.id,
        }
        postFetch(api_order_workorder_workorderDetail, params, {
            success: (response) => {
                this.setState({
                    data: response.result,
                    list: response.result.element
                }, () => {
                    this.state.inputValue = []
                    for (let i = 0, len = this.state.list.length; i < len; i++) {
                        this.state.inputValue.push('')
                    }
                })
            },
            fail: (response) => {
                show(response.result.message);
            }
        })
    }

    getFileImageView() {
        let views = []
        if (this.state.data.file && this.state.data.file.length > 0) {
            for (let i = 0, len = this.state.data.file.length; i < len; i++) {
                let item = this.state.data.file[i];
                views.push(
                    <TouchableOpacity key={i} style={{ width: 105 * unitWidth, height: 72 * unitWidth, marginTop: 10 * unitWidth, marginRight: 10 * unitWidth }}
                        onPress={() => {
                            this.props.navigation.navigate('BigImageList', { imageList: this.state.data.file })
                        }} activeOpacity={0.7}>
                        <FastImage
                            style={{ width: 105 * unitWidth, height: 72 * unitWidth }}
                            source={{ uri: item }} resizeMode={FastImage.resizeMode.cover} />
                    </TouchableOpacity>
                );
            }
        }
        return views
    }

    submit() {
        let element_list = []
        for (let i = 0, len = this.state.list.length; i < len; i++) {
            let item = this.state.list[i];
            element_list.push({
                title: item.name + '(' + item.count + '个)',
                price: this.state.inputValue[i]
            })
        }
        let params = {
            'work_order_id': this.id,
            'element_list': JSON.stringify(element_list),
            'total_price': this.state.money,
            'delivery_date': this.state.delivery_date,
            'remark': this.state.remark,
        }
        postFetch(api_order_workorder_offer, params, {
            success: (response) => {
                // show(response.result.message);
                this.refs.CommonModal3.showModal();
            },
            fail: (response) => {
                show(response.result.message);
            }
        })
    }
}